/**
 * Created by John on 2016/7/13.
 */
var MongoClient = require('mongodb').MongoClient;
var mongo = new MongoClient();
var myDB = null;

mongo.connect('mongodb://localhost/', function (err, db) {
    myDB = db.db('BeginningMongoDB');
    myDB.collection('word_stats', function (err, collection) {
        limitResults(collection, 1);
    });
});

function limitResults(collection, limit, myDB) {
    var query = {first: 'a'};
    var cursor = collection.find(query);
    cursor.limit(limit);
    console.log();
    console.log('words limited to ' + limit + ':');
    if (limit < 7) {
        displayCursor(cursor, limitResults, collection, limit + 2);
    } else {
        displayCursor(cursor, limitResults);
    }
}

function displayCursor(cursor, callback, collection, limit) {
    cursor.toArray(function (err, items) {
        var wordStr = '';
        for (var i in items) {
            wordStr += items[i].word + ',';
        }
        if (wordStr.length > 23) {
            wordStr = wordStr.slice(0, 23) + '...';
        }
        console.log(wordStr);
        if (collection) {
            callback(collection, limit);
        } else {
            myDB.close();
        }
    });
}